package com.yz.forlogin.security.controller;


import com.yz.common.pojo.ResultCode;
import com.yz.forlogin.security.entity.User;
import com.yz.forlogin.security.utils.JwtTokenUtils;
import com.yz.forlogin.system.service.UserService;
import io.jsonwebtoken.ExpiredJwtException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @author 钰杰
 */
@RestController
@RequestMapping("/auth")
@Slf4j
public class AuthController {


    private final UserService userService;

    public AuthController(UserService userService) {
        this.userService = userService;
    }

    @PostMapping("/register")
    public ResponseEntity registerUser(@RequestBody Map<String, String> registerUser) {
        userService.saveUser(registerUser);
        return ResponseEntity.ok().build();
    }

    @PostMapping("/getUserInfo")
    public User getUserInfo(@RequestParam("username") String username) {
        User userInfoByUsername = userService.getUserInfoByUsername(username);
        return userInfoByUsername;
    }

    @GetMapping("feign_token/{token}")
    public Map getUserRolesByToken(@PathVariable String token) {
        Map<String, Object> map = new HashMap<>();
        List<SimpleGrantedAuthority> userRolesByToken = null;
        try {
            userRolesByToken = JwtTokenUtils.getUserRolesByToken(token);
        } catch (Exception e) {
            log.error("当前Token已过期："+ ResultCode.ERROR_TOKEN_EXCEEDED_CODE);
            map.put("error",ResultCode.ERROR_TOKEN_EXCEEDED_CODE);
        }
        map.put("userRolesByToken",userRolesByToken);
        return map;
    }

}